package com.hw.utils.forkjoinpool;

import java.util.concurrent.RecursiveAction;

/**
 * @program: hwUtils
 * @description:
 * @author: hewei
 * @date: 2023-03-16 11:20
 * 无返回值的迭代任务：多线程分解打印数列，数列范围  [start,end]
 * 每个线程打印 step（20） 个数字
 **/
public class RecursiveActionWorker extends RecursiveAction {
    private static final int step = 20;

    private int start;
    private int end;

    public RecursiveActionWorker(int start, int end) {
        this.start = start;
        this.end = end;
    }

    @Override
    protected void compute() {
        //当end-start的值小于MAX时，开始打印
        if ((end - start) < step) {
            for (int i = start; i < end; i++) {
                System.out.println(Thread.currentThread().getName() + " 输出值：" + i);
            }
        } else {
            // 将大任务分解成两个小任务
            int middle = (start + end) / 2;
            RecursiveActionWorker left = new RecursiveActionWorker(start, middle);
            RecursiveActionWorker right = new RecursiveActionWorker(middle, end);
            /* 开启新线程分支 */
            left.fork();
            right.fork();
        }
    }
}
